package com.example.materialmotiondemo.ui

import android.annotation.SuppressLint
import android.content.Context
import android.view.Gravity
import android.widget.Toast

object ToastUtils {

    @JvmField
    var isShow = true

    @JvmField
    var messageOld: String? = null

    @JvmField
    var time: Long = 0

    @JvmField
    var toast: Toast? = null

    /**
     * 短时间显示Toast
     * @param context
     * @param message 显示字符串
     * @param gravity 显示位置
     */
    private fun showShort(context: Context?, message: CharSequence, gravity: Int) {
        showToast(context, message, gravity, Toast.LENGTH_SHORT)
    }

    /**
     * 短时间显示Toast
     * @param context
     * @param message 显示字符串
     * @param gravity 显示位置
     * @param duration 持续时间
     */
    @SuppressLint("ShowToast")
    fun showToast(context: Context?, message: CharSequence, gravity: Int, duration: Int) {
        if (isShow) {
            if (toast == null) {
                /*toast为空新建*/
                toast = Toast.makeText(context, message, duration)
                toast?.setGravity(gravity, 0, 0)
                time = System.currentTimeMillis()
            } else if (message.toString() != messageOld) {
                /*如果本次弹出数据与上一次不同，则取消正在弹出的toast，重新弹出*/
                toast?.cancel()
                toast = Toast.makeText(context, message, duration)
                toast?.setGravity(gravity, 0, 0)
                time = System.currentTimeMillis()
            } else {
                /*防止重复弹出*/
                if (System.currentTimeMillis() - time > 2000) {
                    toast?.cancel()
                    toast = Toast.makeText(context, message, duration)
                    toast?.setGravity(gravity, 0, 0)
                    time = System.currentTimeMillis()
                }
            }
            toast?.show()
            messageOld = message.toString()
        }

    }

    /**
     * 短时间显示Toast
     * @param context
     * @param message 显示字符串
     */
    fun showShort(context: Context?, message: CharSequence) {
        showShort(context, message, Gravity.BOTTOM)
    }

    /**
     * 短时间显示Toast
     * @param context
     * @param message 显示字符串
     */
    fun showShortCenter(context: Context?, message: CharSequence) {
        showShort(context, message, Gravity.CENTER)
    }

    /**
     * 长时间Toast
     * @param context
     * @param message 显示字符串
     */
    fun showCenterLong(context: Context?, message: CharSequence) {
        showToast(context, message, Gravity.CENTER, Toast.LENGTH_LONG)
    }


    /**
     * 长时间Toast
     * @param context
     * @param message 显示字符串
     */
    fun showShortLong(context: Context?, message: CharSequence) {
        showToast(context, message, Gravity.BOTTOM, Toast.LENGTH_LONG)
    }

}